package com.example.blog_system.service.impl;

import com.github.pagehelper.PageHelper;
import com.example.blog_system.dao.ArticleMapper;
import com.example.blog_system.dao.CommentMapper;
import com.example.blog_system.dao.StatisticMapper;
import com.example.blog_system.model.ResponseData.StaticticsBo;
import com.example.blog_system.model.domain.Article;
import com.example.blog_system.model.domain.Comment;
import com.example.blog_system.model.domain.Statistic;
import com.example.blog_system.service.ISiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SiteServiceImpl implements ISiteService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private StatisticMapper statisticMapper;

    @Override
    public List<Comment> recentComments(int limit) {
        PageHelper.startPage(1, limit > 10 || limit < 1 ? 10 : limit);
        List<Comment> byPage = commentMapper.selectNewComment( ) ;
        return byPage;

    }

    @Override
    public List<Article> recentArticles(int limit) {
        PageHelper.startPage( 1, limit > 10 || limit < 1 ? 10 : limit);
        List<Article> list = articleMapper.selectArticleWithPage() ;
        //封装统计数据
        return pageList(list);

    }
    //封装统计数据
    private List<Article> pageList(List<Article> list) {
        for (int i = 0; i < list.size(); i++) {
            Article article = list.get(i);
            Statistic statistic = statisticMapper.selectStatisticWithArticleId(article.getId());
            article.setHits (statistic.getHits());
            article.setCommentsNum( statistic.getCommentsNum());
        }
        return list;
    }

    @Override
    public StaticticsBo getStatistics() {
        StaticticsBo staticticsBo = new StaticticsBo();
        Integer articles = articleMapper.countArticle();
        Integer comments = commentMapper.countComment();
        staticticsBo.setArticles(articles);
        staticticsBo.setComments(comments);
        return staticticsBo;
    }


    @Override
    public void updateStatistics(Article article) {

    }
}
